package com.xiao.mall.message.service.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author mingyuezheng
 * 发货提醒
 */

@Slf4j
@Component
public class BaseNotificationHandler {


    @Value("${tencent.cloud.tpns.api-url:}")
    private String apiUrl;
    @Value("${tencent.cloud.tpns.push-url:}")
    private String pushUrl;


    private final RestTemplate restTemplate;

    public BaseNotificationHandler(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public boolean pushNotification(String accessId, String sign, String requestStr, long timeStamp) {

        boolean isPush = false;
        HttpHeaders headers = new HttpHeaders();
        headers.add("AccessId", accessId);
        headers.add("Sign", sign);
        headers.add("TimeStamp", String.valueOf(timeStamp));
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> stringHttpEntity = new HttpEntity<>(requestStr, headers);
        ResponseEntity<Map> responseEntity =
                restTemplate.exchange(apiUrl + pushUrl, HttpMethod.POST, stringHttpEntity, Map.class);

        if (log.isDebugEnabled()) {
            log.debug("call send result: {}", responseEntity);
        }

        if (responseEntity.hasBody()) {
            Map map = responseEntity.getBody();
            log.info ("[message]-[notification]-移动推送TPNS, 请求内容: {}\"", requestStr);
            int retCode = (Integer) map.get("ret_code");
            log.info("[message]-[notification]-移动推送TPNS, 腾讯响应内容: {}", map);
            if (retCode == 0) {
                isPush = true;
            }
        }

        return isPush;
    }

}
